package top.ruanlitao.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ruanlitao.shortlink.admin.common.biz.user.UserContext;
import top.ruanlitao.shortlink.admin.common.constant.RedisCacheConstant;
import top.ruanlitao.shortlink.admin.common.convention.exception.ClientException;
import top.ruanlitao.shortlink.admin.common.convention.result.Result;
import top.ruanlitao.shortlink.admin.common.enums.GroupErrorCodeEnum;
import top.ruanlitao.shortlink.admin.dao.entity.GroupDO;
import top.ruanlitao.shortlink.admin.dao.mapper.GroupMapper;
import top.ruanlitao.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import top.ruanlitao.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import top.ruanlitao.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import top.ruanlitao.shortlink.admin.remote.ShortLinkActualRemoteService;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import top.ruanlitao.shortlink.admin.service.GroupService;
import top.ruanlitao.shortlink.admin.toolkit.RandomGenerator;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 分组接口实现层
 */
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    // 短链接中台远程调用服务（使用 SpringCloud OpenFeign）
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String name) {
        saveGroup(UserContext.getUsername(), name);
    }

    @Override
    public void saveGroup(String username, String name) {
        // 获取到分布式锁，目的是为了防止同一用户在多端登录的情况下同时创建分组导致分组数量超过最大限制
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            // 查询分组数量是否超过了最大分组数量
            String count = stringRedisTemplate.opsForValue().get(String.format(RedisCacheConstant.GROUP_COUNT_KEY, username));
            if (count == null) {
                LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                        .eq(GroupDO::getUsername, username);
                List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
                if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                    stringRedisTemplate.opsForValue().set(String.format(RedisCacheConstant.GROUP_COUNT_KEY, username), String.valueOf(groupMaxNum));
                    throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
                } else {
                    count = CollUtil.isEmpty(groupDOList) ? "0" : String.valueOf(groupDOList.size());
                    stringRedisTemplate.opsForValue().set(String.format(RedisCacheConstant.GROUP_COUNT_KEY, username), count);

                }
            } else {
                if (Integer.valueOf(count).equals(groupMaxNum)) {
                    throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
                }
            }
            // 随机生成 gid
            String gid;
            // 确保 gid 不重复
            do {
                // gid 为 username + 随机 4 位字符串
                gid = username + RandomGenerator.generateRandom(4);
            } while (isGidExisted(username, gid));
            // 创建 groupDO 对象
            GroupDO groupDO = GroupDO.builder()
                    .gid(gid)
                    .name(name)
                    .username(username)
                    .sortOrder(0)
                    .build();
            // 插入数据
            baseMapper.insert(groupDO);
            // 更新 Redis 中分组数量
            stringRedisTemplate.opsForValue().increment(String.format(RedisCacheConstant.GROUP_COUNT_KEY, username));
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder)
                .orderByAsc(GroupDO::getUpdateTime);
        // 查询到分组信息
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        // 调用中台的接口获取每个分组下短链接的数量
        Result<List<ShortLinkGroupCountQueryRespDTO>> remoteResult = shortLinkActualRemoteService.listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        // 将分组信息转为响应的数据
        List<ShortLinkGroupRespDTO> results = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        // TODO 遍历分组数据，为每个分组赋上其下的短链接数量（后面找一下优雅一点的写法）
        results.forEach(each -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = remoteResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid()))
                    .findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return results;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid());
        int update = baseMapper.update(
                GroupDO.builder().name(requestParam.getName()).build(),
                updateWrapper
        );
        if (update != 1) {
            throw new ClientException(GroupErrorCodeEnum.GROUP_UPDATE_ERROR);
        }
    }

    @Override
    public void deleteGroup(String gid) {
        baseMapper.delete(
                Wrappers.lambdaQuery(GroupDO.class)
                        .eq(GroupDO::getGid, gid)
                        .eq(GroupDO::getUsername, UserContext.getUsername())
        );
        String count = stringRedisTemplate.opsForValue().get(String.format(RedisCacheConstant.GROUP_COUNT_KEY, UserContext.getUsername()));
        if (count != null) {
            if (Integer.parseInt(count) != 0) {
                stringRedisTemplate.opsForValue().decrement(String.format(RedisCacheConstant.GROUP_COUNT_KEY, UserContext.getUsername()));
            } else {
                stringRedisTemplate.delete(String.format(RedisCacheConstant.GROUP_COUNT_KEY, UserContext.getUsername()));
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        if (CollUtil.isEmpty(requestParam)) {
            throw new ClientException("分组不能为空");
        }
        requestParam.forEach(each -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid());
            baseMapper.update(groupDO, updateWrapper);
        });
    }

    /**
     * 查询 gid 是否存在（同个用户下的 gid 不能重复）
     *
     * @param username 用户名
     * @param gid 分组id
     * @return gid 是否存在，存在：true，不存在：false
     */
    private Boolean isGidExisted(String username, String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers
                .lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, username)
                .eq(GroupDO::getGid, gid);
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO != null;
    }
}
